<template>
  <h1>
    图书管理系统
  </h1>
  <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="150px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
  >
    <el-form-item label="账号" prop="username">
      <el-input v-model="ruleForm.username" style="width: 200px" />
    </el-form-item>

    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="ruleForm.password" show-password style="width: 200px" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="isLoading">
        登录
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/utils/request.js'
import { ElMessage } from 'element-plus'
import {useRouter} from "vue-router";
import useUser from '@/stores/user.js'

// 页面跳转
const router = useRouter();

const userStore=useUser();

let isLoading=ref(false);

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  username: '',
  password: '',
})

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  isLoading.value=true;
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      request.post('/user/login',{
        username:ruleForm.username,
        password:ruleForm.password
      }).then((res)=>{
          console.log("res:",res);
          if(res.code===0){
            isLoading.value=false;
            ElMessage({
              message: '登陆成功',
              type: 'success',
            })
            localStorage.setItem('token',res.data.jwt)
            router.push("/");
            userStore.$patch({
              userInfo: res.data
            })
          }else{
            isLoading.value=false;

            ElMessage({
              message: `${res.msg}`,
              type: 'error',
            })
          }
      }).catch((err)=>{
          console.log("err:",err);
        ElMessage({
          message: '登陆失败，请联系管理员',
          type: 'error',
        })
      })
    } else {
      console.log('error submit!', fields)
      isLoading.value=false;
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))
</script>